package com.example.pei.ithinklearnt.view.activity;

import android.Manifest;
import android.content.Intent;
import android.graphics.Color;
import android.support.annotation.NonNull;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.example.pei.ithinklearnt.AppApplication;
import com.example.pei.ithinklearnt.R;
import com.example.pei.ithinklearnt.model.UserModel;
import com.example.pei.ithinklearnt.view.base.RegisterBaseActivity;

import butterknife.BindView;
import butterknife.OnClick;
import cn.bmob.sms.BmobSMS;
import cn.bmob.sms.listener.RequestSMSCodeListener;
import cn.bmob.sms.listener.VerifySMSCodeListener;
import pub.devrel.easypermissions.AfterPermissionGranted;
import pub.devrel.easypermissions.EasyPermissions;

import static com.example.pei.ithinklearnt.utils.MyUtils.checkPassword;
import static com.example.pei.ithinklearnt.utils.MyUtils.isMobileNO;
import static com.example.pei.ithinklearnt.utils.PermisionUtil.hasReadPhoneStatePermission;
import static com.example.pei.ithinklearnt.utils.ToastUtil.ToastShow;

public class RegisterOneActivity extends RegisterBaseActivity {

    @BindView(R.id.et_phone)
    EditText editTextPhone;
    @BindView(R.id.ed_password)
    EditText editTextPasswd;

    @BindView(R.id.ed_code)
    EditText editTextCode;
    @BindView(R.id.btn_next)
    Button buttonNext;
    @BindView(R.id.btn01)
    Button buttonSendCode;


    private static final int RC_READ_PHONE_STATE_PERM = 124;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_register_one);
        setListeners();
    }


    @Override
    public void onRequestPermissionsResult(int requestCode,
                                           @NonNull String[] permissions,
                                           @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
    }



    //清除手机号
    @OnClick(R.id.btn_delePhone)
    void clearPhone(){
        editTextPhone.setText("");
    }
    //清除密码
    @OnClick(R.id.btn_delePasswd)
    void clearPasswd(){
        editTextPasswd.setText("");
    }
    //返回
    @OnClick(R.id.btn_back_to_menu)
    void back(){
        finish();
    }

    //下一步
    @OnClick(R.id.btn_next)
    void toNext(){
        final String phone=editTextPhone.getText().toString();
        final String code=editTextCode.getText().toString();
        final String passWord=editTextPasswd.getText().toString();

        if(phone.equals("")||code.equals("")||passWord.equals("")){
            Toast.makeText(RegisterOneActivity.this,"请填写手机号、密码、验证码",Toast.LENGTH_SHORT).show();
            return;
        }
        if(!checkPassword(passWord)){
            Toast.makeText(RegisterOneActivity.this,"密码不符合要求(不能输入空格符)",Toast.LENGTH_SHORT).show();
            return;
        }

        BmobSMS.verifySmsCode(RegisterOneActivity.this,phone ,code, new VerifySMSCodeListener() {
            @Override
            public void done(cn.bmob.sms.exception.BmobException e) {
                if(e==null){
                    //短信验证码验证成功
                    Intent intent=new Intent("register_step_4_Activity");
                    intent.putExtra("phoneString",phone);
                    intent.putExtra("passWordString",passWord);
                    RegisterOneActivity.this.startActivity(intent);
                }else{
                    Toast.makeText(RegisterOneActivity.this,"验证码错误",Toast.LENGTH_SHORT).show();
                }
            }
        });
    }


    //获取验证码
    @OnClick(R.id.btn01)
    @AfterPermissionGranted(RC_READ_PHONE_STATE_PERM)
    public void readPhoneStateTask() {
        if (hasReadPhoneStatePermission(this)) {
            //如果有权限
            sendCode();
        } else {
            // Ask for both permissions
            EasyPermissions.requestPermissions(
                    this,
                    "需要你的手机号否则将无法接收到验证码.",
                    RC_READ_PHONE_STATE_PERM,
                    Manifest.permission.READ_PHONE_STATE);
        }
    }

    private void setListeners(){
        editTextPhone.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if(isMobileNO(editTextPhone.getText().toString())){
                    //是手机号
                    buttonSendCode.setTextColor(Color.parseColor("#282828"));
                    buttonSendCode.setClickable(true);
                }else{
                    //不是手机号
                    buttonSendCode.setTextColor(Color.parseColor("#808080"));
                    buttonSendCode.setClickable(false);
                }
            }
        });
    }


    //发送验证码
    void sendCode(){
        buttonSendCode.setClickable(false);
        final String phone=editTextPhone.getText().toString();
        UserModel.getInstance().isPhoneRegistered(phone, new UserModel.isPhoneRegisteredListerner() {
            @Override
            public void isRegistered() {
                ToastShow(AppApplication.getContext(),"该手机号已经被注册",0);
                buttonSendCode.setClickable(true);
            }
            @Override
            public void noRegistered() {
                //更改button的样式
                changeBtnGetCode();
                //如果手机号没有被注册，可以发送验证码
                BmobSMS.requestSMSCode(RegisterOneActivity.this, phone, "交友神器",new RequestSMSCodeListener() {
                    @Override
                    public void done(Integer smsId, cn.bmob.sms.exception.BmobException e) {
                        if (e == null) {
                            ToastShow(AppApplication.getContext(),"正在发送,请稍后...",0);
                            buttonSendCode.setClickable(false);
                        }
                        else if(e.getErrorCode()==10010){
                            toast("该手机号发送短信达到限制，请等待一段时间");
                        }
                        else{
                            ToastShow(AppApplication.getContext(),"发送失败 Code:"+e.getMessage(),0);
                            buttonSendCode.setClickable(true);
                        }
                    }
                });
            }
            @Override
            public void failed() {
                ToastShow(AppApplication.getContext(),"未能发送成功，尝试检查网络",0);
                buttonSendCode.setClickable(true);
            }
        });
    }

    //每次验证请求需要间隔35S
    private int time=60;
    //控制按钮样式是否改变
    private boolean tag = true;

    public void changeBtnGetCode() {
        Thread thread = new Thread() {
            @Override
            public void run() {
                if (tag) {
                    while (time > 0) {
                        setWaitSendAgain(--time);
                        try {
                            Thread.sleep(1000);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                    tag = false;
                }
                time = 60;
                tag = true;

                setCanSendAgain();

            }
        };
        thread.start();
    }

    private void setWaitSendAgain(final int time) {

        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                buttonSendCode.setText(getResources().getString(R.string.sendagain,time));
                buttonSendCode.setClickable(false);
                buttonSendCode.setTextColor(Color.parseColor("#aaaaaa"));
            }
        });
    }
    private void setCanSendAgain() {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                buttonSendCode.setText("重新发送");
                buttonSendCode.setClickable(true);
                buttonSendCode.setTextColor(Color.parseColor("#333333"));
            }
        });
    }


}
